/**
 * @file userApp.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2022-10-20
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <string.h>
#include "OSAL.h"
#include "log.h"
#include "stdio.h"
#include "rtc.h"
#include "userApp.h"
#include "save.h"
// #include "simpleBLEPeripheral.h"
#include "peripheral.h"
#include "gap.h"
#include "uart_process.h"
// #include "halPeripheral.h"
#include "Display.h"
#include "user_prcess.h"
#include "readFlash.h"
#include  "clock.h"
#include "pwrmgr.h"
// #include "Xiaobai1248.h"
// #include "ScanAndConnect.h"
#include "UserKvSave.h"
#include "user_Bz.h"
// #include "s_sample.h"
#include "watchdog.h"
//----------------------------------------------------------
uint8_t UseAPP_TaskID;
//----------------------------------------------------------
#define REFLASH_RTC_TIMEMS  30000 // 60000 //300000      //   x ms
//----------------------------------------------------------
/**
 * @fn      void sample_wdt_init( void )
 * @brief   watchdog initialization
 * @param   none
 * @return  none
 */
void sample_wdt_init( void )
{
	HalWdtInit(ENABLE, WDG_USE_POLLING_MODE, NULL);
	LOG("WDT Init\r\n");
}
//----------------------------------------------------------
void UserAppPrcess_Init(uint8 task_id)
{
    UserProcess.ProcessFlag.flagBit.PowerON = false;
    if(!g_system_reset_cause)
        UserProcess.ProcessFlag.flagBit.PowerON = TRUE;
    UseAPP_TaskID = task_id;
    sample_wdt_init();
    UserFlashSaveInit();
    UserHalRtcInit();
	KeyPinInt();

    // osal_start_reload_timer(UseAPP_TaskID, UserAppEvent_ReflashRTC, REFLASH_RTC_TIMEMS);
    // osal_start_reload_timer(UseAPP_TaskID, UserAppEvent_TestTSB, 5000);
    osal_start_timerEx(UseAPP_TaskID, UserAppEvent_PROCESS, NULL);
    // osal_start_reload_timer(UseAPP_TaskID, UserAppEvent_TimeClrKey, 128);
}

uint16 UserApp_ProcessEvent(uint8 task_id, uint16 events)
{
    static uint8 utcDelay = 0;
    if (task_id != UseAPP_TaskID)
    {
        return 0;
    }
    if (events & SYS_EVENT_MSG)
    {
        osal_event_hdr_t *pMsg;

        if ((pMsg = (osal_event_hdr_t *)osal_msg_receive(UseAPP_TaskID)) != NULL)
        {
            LOG("sys_event_msg:UserAPP_TaskID=%d\r\n", UseAPP_TaskID);
            // Process incoming messages
            switch (pMsg->event)
            {
            // Incoming GATT message
            case GATT_MSG_EVENT:
                // gattServApp_ProcessMsg( (gattMsgEvent_t *)pMsg );
                break;

            default:
                // Unsupported message
                break;
            }
            ///< Release the OSAL message
            VOID osal_msg_deallocate((uint8 *)pMsg);
        }

        ///< return unprocessed events
        return (events ^ SYS_EVENT_MSG);
    }

    if (events & UserAppEvent_INIT_FACTORY)
    {
        // Reset2FactoryMode();
        return (events ^ UserAppEvent_INIT_FACTORY);
    }

    // if (events & UserAppEvent_TestTSB)
    // {
    //     // tsdb_test_set(&xTsdb,HalRtcGetUtcOnly());
    //     return (events ^ UserAppEvent_TestTSB);
    // }

    if (events & UserAppEvent_ReadHistory)
    {
        // if(Usertsdb_readHistory(1,&xTsdb,NULL,NULL))
        //     useApp_task_set(USER_TASK_START,UserAppEvent_ReadHistory,500);
        // else
        // {
        //     // HalTaskFlag &= (~B_HALTASKFLAG_SEND_HISTORY);                      //清除读取记录标志
        //     useApp_task_set(USER_TASK_STOP,UserAppEvent_ReadHistory,NULL);
        // }
        return (events ^ UserAppEvent_ReadHistory);
    }

    if (events & UserAppEvent_PROCESS)
    {
        HalWdtFeed();
        FunUserProcess();
        osal_start_timerEx(UseAPP_TaskID, UserAppEvent_PROCESS, 16);
        return (events ^ UserAppEvent_PROCESS);
    }

    if (events & UserAppEvent_ReflashRTC)
    {
        UTCTime *prtcValue = NULL;
        UTCTimeStruct setTime;
        // struct fdb_blob blob;
        prtcValue = osal_mem_alloc(sizeof(UTCTime));
        if (prtcValue)
        {
            *prtcValue = HalRtcGet_Utc() - UTC_1970TO2000_SECOND;
            // *prtcValue = HalRtcGet_Utc();
            LOG("Read UTC = 0x%X\r\n", *prtcValue);
            osal_ConvertUTCTime(&setTime, *prtcValue);
            utcDelay++;
            // if (utcDelay == 1)
            // {
            //     // tsdb_test_QUERY(&xTsdb);
            //     Usertsdb_readHistory(0, &xTsdb, 0, 0x29628D49);
            //     //    Usertsdb_readHistory(1,&xTsdb,NULL,NULL);
            //     osal_start_timerEx(UseAPP_TaskID, UserAppEvent_ReadHistory, 500);
            // }
            if (utcDelay > 7)
            {
                user_get_env_blob(UTC_TIME_KEY,prtcValue,sizeof(UTCTime));            
                utcDelay = 0;
            }      
            osal_mem_free(prtcValue);
            LOG("save delay=%d reload rtc: %d/%d/%d %d:%d:%d\r\n", utcDelay, setTime.year, setTime.month + 1, setTime.day + 1, setTime.hour, setTime.minutes, setTime.seconds);
        }
        else
        {
            LOG("rtc value alloc err\r\n");
        }
        return (events ^ UserAppEvent_ReflashRTC);
    }
    if (events & UserAppEvent_POWER_ON)
    {
        if (!UserFlag.flagBit.on)
        {
            UserFlag.flagBit.on = true;
            useApp_task_set(USER_TASK_START, UserAppEvent_PROCESS, NULL);
            SwitchUseProcess(D_USER_PROCESS_ON); // pre for weakup
        }
        return (events ^ UserAppEvent_POWER_ON);
    }

    if (events & UserAppEvent_POWER_OFF)
    {
        UserFlag.flagBit.on         = false;
        UserFlag.flagBit.WeakMcu    = false;
        useApp_task_set(USER_TASK_STOP, UserAppEvent_PROCESS, NULL);
        User_BZ_t   bzData;
        bzData.flag = 0;
        Bz_init_ONOFF(bzData);
        // Tm1640_IO_PowerDown();
        // CH456_IO_PowerDown();
        DisplayDriverPowerDown();
        KeyPowerDown();
        WaitUs(100);
        pwroff_cfg_t cfg;        
        cfg.pin = KeyOnOffPin;
        cfg.type = POL_FALLING;
        cfg.on_time = 100;                
        hal_pwrmgr_poweroff(&cfg, 1);
        return (events ^ UserAppEvent_POWER_OFF);
    }

    // if (events & UserAppEvent_INIT_MEMINFOR)
    // {
    //     // if (!ReadMemoryInfor(&userMemoryInfor))
    //     // {
    //     //     userMemoryInfor.MemoryIndex = 0;
    //     //     userMemoryInfor.MemoryTotal = 0;
    //     //     WriteMemoryInfor(&userMemoryInfor);
    //     // }
    //     return (events ^ UserAppEvent_INIT_MEMINFOR);
    // }

    // if (events & UserAppEvent_INIT_USER)
    // {
    //     // if (InitUserInfor())
    //     //     useApp_task_set(USER_TASK_START, UserAppEvent_INIT_USER, 64);
    //     // else
    //     //     useApp_task_set(USER_TASK_STOP, UserAppEvent_INIT_USER, NULL);
    //     return (events ^ UserAppEvent_INIT_USER);
    // }
    if (events & UserAppEvent_TimeClrKey)
    {
        // KeyFlag = 0; // overtime clear key flag
        // attMsg_t sendMsg;
        // KeyFlag++;
        // sendMsg.writeReq.value[0] = 0xAC;
        // sendMsg.writeReq.value[1] = 0x02;
        // sendMsg.writeReq.value[2] = 0x0F;
        // sendMsg.writeReq.value[3] = KeyFlag;
        // sendMsg.writeReq.len = 4;
        // user_data_send_by_ble(LL_ROLE_MASTER, 0, &sendMsg);
        return (events ^ UserAppEvent_TimeClrKey);
    }
    if (events & UserAppEvent_ReadFlash)
    {
        if(ReadFlashAndPrint())
            useApp_task_set(USER_TASK_START,UserAppEvent_ReadFlash,32);
        return (events ^ UserAppEvent_ReadFlash);
    }

    if( events & UserAppEvent_Bz)
    {
        if(!UserProcess.ProcessFlag.flagBit.idle)
            BZ_Precss();
        return ( events ^ UserAppEvent_Bz);
    }

    return 0;
}

/**
 * @fn		void peripheral_task_set(uint8 action, uint16 event, uint32 time)
 * @brief
 * @param	none
 * @return	none
 */
void useApp_task_set(uint8 action, uint16 event, uint32 time)
{
    osal_stop_timerEx(UseAPP_TaskID, event);
    if (action == USER_TASK_START)
    {
        if (time)
        {
            osal_start_timerEx(UseAPP_TaskID, event, time);
        }
        else
        {
            osal_set_event(UseAPP_TaskID, event);
        }
    }
}
